package com.secneo.appshare.activities;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;

import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.KeyEvent;
import android.view.Window;
import android.view.WindowManager;

import com.secneo.appshare.AppShareApplication;
import com.secneo.appshare.R;
import com.secneo.appshare.api.LocalStore;
import com.secneo.appshare.common.ActivityUtil;
import com.secneo.appshare.common.Constants;
import com.secneo.appshare.common.Util;
import com.secneo.appshare.service.AppShareService;
import com.secneo.mp.MpApi;
import com.secneo.mp.api.util.MpUtil;
import com.secneo.mp.api.view.MpMessage;

public class SplashActivity extends Activity
{
	private static final String FIRST_CONFIG_MESSAGE = "first_config_message";
	int firstId = 0;
	private static final String CHANNEL_ID = "channel_id";
	
	private boolean is_exit = false ;

	final Handler handler = new Handler()
	{

		@Override
		public void handleMessage(Message msg)
		{
			Intent intent = new Intent();
			switch (msg.what)
			{
				case Constants.MSG_GOTO_MAIN:
					if(!is_exit){
						intent.setClass(SplashActivity.this, MainActivity.class);
						startActivity(intent);
						finish();
					}
					break;

			}
			super.handleMessage(msg);
		}
	};

	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState)
	{
		super.onCreate(savedInstanceState);
		getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.appshare_splash);
		
		AppShareApplication.getInstance().addActivity(this);
		startService(new Intent(this, AppShareService.class));

		if (!(LocalStore.getLocaleStoreInstance(SplashActivity.this).ApplicationShortCutCreated()))
		{
			ActivityUtil.creatShortcut(SplashActivity.this, SplashActivity.this.getResources().getString(R.string.app_name), SplashActivity.this.getResources().getDrawable(R.drawable.icon), Constants.PACKAGENAME,
					"com.secneo.appshare.activities.SplashActivity");
			LocalStore.getLocaleStoreInstance(SplashActivity.this).setApplicationShortCutCreated(true);
		}

		if (ActivityUtil.getNetworkState(this) != 0)
		{
			Thread pioneerThread = new Thread()
			{
				public void run()
				{
					try
					{
						ActivityUtil.getPolicyUrl(SplashActivity.this);
						submitChannelId();
					} catch (Exception ex)
					{
						ex.printStackTrace();
					}
				}
			};
			pioneerThread.start();
			// 记录开机启动
			MpUtil.setMobileVersion(String.valueOf(Constants.VERSION_CODE));
			MpUtil.setPackageName(Constants.PACKAGENAME);
			MpUtil.setUrl(Constants.MP_URL);
			MpUtil.DEBUG = true;
			MpMessage.onCreateMpDynamic(SplashActivity.this);
			com.secneo.mp.api.database.DatabaseHelper dh = new com.secneo.mp.api.database.DatabaseHelper(SplashActivity.this);
			dh.insertUserAppPopularityByAppOpenTime(SplashActivity.this, 100);
			dh.close();

		}

		Thread t = new Thread()
		{
			public void run()
			{
				try
				{
					Util.clearLargeCache(SplashActivity.this);
					Thread.sleep(3000);
					Message msg = new Message();
					msg.what = Constants.MSG_GOTO_MAIN;
					handler.sendMessage(msg);
					return;

				} catch (Exception ex)
				{
					Log.d("MyTag", "Splash error:"+ex.getMessage());
					ex.printStackTrace();
				}
			}
		};
		t.start();

	}

	private void submitChannelId()
	{
		SharedPreferences saving = getSharedPreferences(FIRST_CONFIG_MESSAGE, 0);
		String currentID = saving.getString(CHANNEL_ID, "");
		Log.d("MyTag", "currentID: " + currentID);

		String channelId = "";
		try
		{
			InputStream is = getAssets().open("channel_id");
			BufferedReader r = new BufferedReader(new InputStreamReader(is));
			channelId = r.readLine();
			is.close();
		} catch (Exception ex)
		{
			Log.d("MyTag", "Read channelId error! ");
		}

		Log.d("MyTag", "newID: " + channelId);
		if (currentID.equals(channelId))
		{
			Log.d("MyTag", "same ID, return");
			return;
		} else
		{
			Log.d("MyTag", "different ID, submit");
			MpApi mp = MpApi.getAPI();

			mp.setUserInfoURL(Constants.ChannelID);
			// mp.setUserInfoURL("http://211.151.134.164/management/mobileUserInfo.do");
			String md5Imei = mp.getPhoneMd5Imei(this);
			String ret = mp.submitChannelID(md5Imei, Constants.PACKAGENAME + "_" + Constants.VERSION_CODE, channelId);
			Log.d("MyTag", "SubmitChannelID result: " + ret);
			if (ret != null)
			{
				if (ret.equals(MpApi.SUCCESS_SUBMIT_CHANNEL_ID))
				{
					saving.edit().putString(CHANNEL_ID, channelId).commit();

					// 静态数据
					MpUtil.setMobileVersion(String.valueOf(Constants.VERSION_CODE));
					MpUtil.setPackageName(Constants.PACKAGENAME);
					MpUtil.setUrl(Constants.MP_URL);
					MpMessage.onCreateMpStatic(SplashActivity.this);
				}
			}
		}
	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0){
			is_exit = true ;
			finish() ;
		}
		return super.onKeyDown(keyCode, event) ;
	}
}